package com.imyuanma.qingyun.fs.util;

import com.imyuanma.qingyun.common.client.ums.LoginUserHolder;
import com.imyuanma.qingyun.common.util.StringUtil;
import com.imyuanma.qingyun.fs.model.FsFile;
import com.imyuanma.qingyun.fs.model.enums.EFsFileStatusEnum;
import com.imyuanma.qingyun.fs.model.enums.EFsFileTypeEnum;
import com.imyuanma.qingyun.fs.model.enums.EFsMediaType;
import com.imyuanma.qingyun.interfaces.ums.model.LoginUserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Calendar;

/**
 * 文件服务工厂对象
 *
 * @author wangjy
 * @date 2022/07/24 12:08:02
 */
public class FsBusinessUtil {
    private static final Logger logger = LoggerFactory.getLogger(FsBusinessUtil.class);
    /**
     * tif格式后缀名
     */
    public static final String TIF_SUFFIX = "tif";

    /**
     * 重写tif文件元数据属性
     *
     * @param tifFsFile    原属性
     * @param formatSuffix 替换的后缀
     */
    public static void rewriteTifFsFile(FsFile tifFsFile, String formatSuffix) {
        tifFsFile.setName(replaceFileSuffix(tifFsFile.getName(), formatSuffix));
        tifFsFile.setSaveName(replaceFileSuffix(tifFsFile.getSaveName(), formatSuffix));
        tifFsFile.setAddr(replaceFileSuffix(tifFsFile.getAddr(), formatSuffix));
        tifFsFile.setPath(replaceFileSuffix(tifFsFile.getPath(), formatSuffix));
    }

    /**
     * 构建文件信息
     *
     * @param file
     * @param folder
     * @param businessCode
     * @return
     */
    public static FsFile buildFsFile(MultipartFile file, FsFile folder, String businessCode) {
        // 文件名
        String fileName = file.getOriginalFilename();
        // 后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String uuid = StringUtil.getUUID();
        // 重写文件名, 实际存储时名字, 避免重名/不合规等问题
        String rewriteName = uuid + suffix;
        Calendar c = Calendar.getInstance();

        // 文件持久化目录, url
        FsFile fsFile = new FsFile();
        fsFile.setId(uuid);
        fsFile.setName(fileName);
        fsFile.setSaveName(rewriteName);
        fsFile.setStatus(EFsFileStatusEnum.NORMAL.getCode());
//        fsFile.setRemark();
        EFsMediaType mediaType = EFsMediaType.ofSuffix(suffix);
        if (mediaType == EFsMediaType.OTHER && ImageUtil.isImageNotThrow(file)) {
            mediaType = EFsMediaType.IMG;
        } else if (mediaType == EFsMediaType.OTHER && StringUtil.isNotBlank(file.getContentType()) && file.getContentType().startsWith("image")) {
            mediaType = EFsMediaType.IMG;
        }
        fsFile.setMediaType(mediaType.getCode());

        fsFile.setFolderId(folder.getId());
        fsFile.setFileSize(file.getSize());
        fsFile.setFileType(EFsFileTypeEnum.FILE.getCode());
        fsFile.setAddr(String.format("%s/%s/%s/%s/%s", folder.getAddr(), c.get(Calendar.YEAR), (c.get(Calendar.MONTH) + 1), c.get(Calendar.DAY_OF_MONTH), rewriteName));
        fsFile.setPath(String.format("%s/%s/%s/%s/%s", folder.getPath(), c.get(Calendar.YEAR), (c.get(Calendar.MONTH) + 1), c.get(Calendar.DAY_OF_MONTH), rewriteName));
        fsFile.setBusinessCode(businessCode);
        LoginUserDTO loginUserDTO = LoginUserHolder.getLoginUser();
        if (loginUserDTO != null) {
            fsFile.setCreateUserId(loginUserDTO.getUserId());
            fsFile.setUpdateUserId(loginUserDTO.getUserId());
        }

        // 图片宽高
        if (EFsMediaType.IMG == mediaType) {
            try {
                BufferedImage image = ImageIO.read(file.getInputStream());
                if (image != null) {
                    fsFile.setImageWidth(image.getWidth());
                    fsFile.setImageHeight(image.getHeight());
                }
            } catch (IOException e) {
                logger.error("[构建文件信息] 获取图片宽高异常", e);
            }
        }
        return fsFile;
    }

    /**
     * 获取对于等级的图片名
     *
     * @param name
     * @param level
     * @return
     */
    public static String getLevelImageName(String name, String level) {
        int idx = name.lastIndexOf(".");
        return name.substring(0, idx) + "_" + level + name.substring(idx);
    }

    /**
     * 获取文件后缀名(不带.)
     *
     * @param name
     * @return
     */
    public static String getFileSuffix(String name) {
        return name.substring(name.lastIndexOf(".") + 1);
    }

    /**
     * 获取文件名(不含扩展名)
     *
     * @param name 文件名, 例如: a.png
     * @return 不含后缀的文件名, 例如: a
     */
    public static String getFileNameNonSuffix(String name) {
        return name.substring(0, name.lastIndexOf("."));
    }

    /**
     * 替换文件后缀名
     *
     * @param name
     * @param suffix
     * @return
     */
    public static String replaceFileSuffix(String name, String suffix) {
        return getFileNameNonSuffix(name) + "." + suffix;
    }

    /**
     * 是否tif格式
     *
     * @param name
     * @return
     */
    public static boolean isTif(String name) {
        return TIF_SUFFIX.equalsIgnoreCase(getFileSuffix(name));
    }

}
